//
//  HPRefreshControl.swift
//  MyWeibo
//
//  Created by apple on 16/4/18.
//  Copyright © 2016年 Apengpeng. All rights reserved.
//

import UIKit

let refreshHeight: CGFloat = 44

// 枚举状态
enum HPRefreshStatue: Int {
    case Normal = 0
    case Pulling = 1
    case reFreshing = 2
}

class HPRefreshControl: UIControl {
    
    // 记录上一次的状态 (可以使用oldValue 和newValue)
//    var lastStatue: HPRefreshStatue = .Normal
    
    var statue: HPRefreshStatue = .Normal {
        
        didSet {
            switch statue {
            case .Normal:
                tipLabel.text = "下拉起飞"
                indicatorView.stopAnimating()
                arrowIcon.hidden = false
                // 当上一次的状态是刷新状态时让它停止
                if oldValue == .reFreshing {
                    UIView.animateWithDuration(0.1, animations: { () -> Void in
                        let top = self.supView.contentInset.top
                        self.supView.contentInset.top = top - refreshHeight
                    })
                    // 效果更好
                    self.arrowIcon.transform = CGAffineTransformIdentity
                }
                
            case .Pulling:
                tipLabel.text = "准备起飞"
                // 旋转箭头
                UIView.animateWithDuration(0.1, animations: { () -> Void in
                    
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .reFreshing:
                tipLabel.text = "正在飞...."
                // 为了在刷新的时候 菊花转,
                indicatorView.startAnimating()
                arrowIcon.hidden = true
                
                // load完毕后需要将状态改为正常, 在load方法中
                // 主动给当前控件发送对应的事件类型, 自动找到target监听的方法
                sendActionsForControlEvents(.ValueChanged)

                // 停止时的高度
                let inSetTop = supView.contentInset.top + refreshHeight
                // 修改高度
                supView.contentInset.top = inSetTop
            }
            
            // 记录上一次状态 , (可以使用oldValue 和newValue)
//            lastStatue = statue
        }
    }
    
    // 重写init 初始化
    override init(frame: CGRect) {
        
        // 系统的刷新按钮高度是固定的, 
        // 可在初始化的时候设置大小, 也可在init 方法中设置frame
        let frameRect = CGRect(x: 0, y: -refreshHeight, width: screenWidth, height: refreshHeight)
        
        super.init(frame: frameRect)
        
        // 设置界面
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 获取父视图的的垂直方法和 -104 进行比较
        let offsetY = supView.contentOffset.y
        let targetRefreshH = -refreshHeight - supView.contentInset.top
        // 监听是否在拖拽视图
//        if supView.dragging 不会修改状态, 因为只是在拖拽的时候执行
        // 添加条件, 当状态是准备刷新时
        if supView.dragging {
            
            if statue == .Pulling && offsetY > targetRefreshH {
                print("普通状态")
                statue = .Normal
            } else if statue == .Normal && offsetY < targetRefreshH {
                print("准备刷新状态")
                statue = .Pulling
            }
            
        } else { // 如果没有拖拽就 刷新
            if statue == .Pulling {
                
                print("正在刷新")
                statue = .reFreshing
                indicatorView.startAnimating()
                arrowIcon.hidden = true
            }
        }
    }
    
    
    func endRefreshing() {
        
        // 延迟执行
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)) * 1)
        dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
            // 修改状态
            self.statue = .Normal
        }
    }
    
    //  使用KVO 监听属性的变化, 移动到视图上的时候调用, 拿到的是父视图,
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        // 获取父视图 就是tableView
        if let supView = newSuperview as? UIScrollView {
            // kvo 监听
            supView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
            
            self.supView = supView
        }
    }
    
    deinit {
        supView.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    private func setupUI() {
        
        backgroundColor = UIColor.purpleColor()
        
        addSubview(indicatorView)
        addSubview(arrowIcon)
        addSubview(tipLabel)
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(10)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
    }
    
    private var supView: UIScrollView = UIScrollView()
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(text: "下拉起飞", textColor: UIColor.blueColor(), fontSzie: 15)
}
